#!/bin/bash

# ERP Mock Server 部署脚本（带环境变量配置）
# 使用方法: bash deploy_with_env.sh

echo "🚀 开始 ERP Mock Server 部署（配置版）..."
echo "=================================================="

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置变量
APP_DIR="/opt/erp-mock"
SERVICE_NAME="erp-mock"
ENV_FILE="$APP_DIR/.env"

# 检查是否为root用户
check_root() {
    if [[ $EUID -eq 0 ]]; then
        echo -e "${RED}❌ 请不要使用root用户运行此脚本${NC}"
        exit 1
    fi
}

# 检查.env文件是否存在
check_env_file() {
    echo -e "${BLUE}🔍 检查环境配置文件...${NC}"

    if [ ! -f "$ENV_FILE" ]; then
        echo -e "${YELLOW}⚠️ 未找到.env文件，将从示例文件创建${NC}"

        if [ -f "$APP_DIR/.env.example" ]; then
            cp "$APP_DIR/.env.example" "$ENV_FILE"
            echo -e "${GREEN}✅ 已从.env.example创建.env文件${NC}"
            echo -e "${YELLOW}⚠️ 请编辑 $ENV_FILE 文件配置你的AppKey和AppSecret${NC}"
            echo -e "${YELLOW}   特别是以下配置项：${NC}"
            echo -e "${YELLOW}   - APP_KEY${NC}"
            echo -e "${YELLOW}   - APP_SECRET${NC}"
            echo ""
            read -p "请确认已配置.env文件，按回车继续..."
        else
            echo -e "${RED}❌ 未找到.env.example文件${NC}"
            exit 1
        fi
    else
        echo -e "${GREEN}✅ 找到环境配置文件: $ENV_FILE${NC}"
    fi
}

# 显示当前配置
show_config() {
    echo -e "${BLUE}📋 当前配置:${NC}"

    # 读取.env文件中的关键配置（不显示密钥）
    if [ -f "$ENV_FILE" ]; then
        echo -e "  APP_KEY: $(grep -E '^APP_KEY=' $ENV_FILE | cut -d'=' -f2)"
        echo -e "  APP_SECRET: $(grep -E '^APP_SECRET=' $ENV_FILE | cut -d'=' -f2 | sed 's/./*/g')"
        echo -e "  APP_NAME: $(grep -E '^APP_NAME=' $ENV_FILE | cut -d'=' -f2)"
        echo -e "  TENANT_ID: $(grep -E '^TENANT_ID=' $ENV_FILE | cut -d'=' -f2)"
        echo -e "  PORT: $(grep -E '^PORT=' $ENV_FILE | cut -d'=' -f2)"
    fi
    echo ""
}

# 停止服务
stop_service() {
    echo -e "${BLUE}🛑 停止服务...${NC}"

    if systemctl is-active --quiet $SERVICE_NAME; then
        sudo systemctl stop $SERVICE_NAME
        echo -e "${GREEN}✅ 服务已停止${NC}"
    else
        echo -e "${YELLOW}⚠️ 服务未运行${NC}"
    fi
}

# 更新systemd服务文件以加载环境变量
update_systemd_service() {
    echo -e "${BLUE}📝 更新systemd服务配置...${NC}"

    cat > /tmp/erp-mock.service << EOF
[Unit]
Description=ERP Mock Server
After=network.target

[Service]
Type=simple
User=$(whoami)
WorkingDirectory=$APP_DIR
EnvironmentFile=$ENV_FILE
ExecStart=$APP_DIR/venv/bin/python main.py
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

    sudo mv /tmp/erp-mock.service /etc/systemd/system/erp-mock.service
    sudo systemctl daemon-reload

    echo -e "${GREEN}✅ systemd服务配置已更新${NC}"
}

# 启动服务
start_service() {
    echo -e "${BLUE}🚀 启动服务...${NC}"

    sudo systemctl start $SERVICE_NAME

    # 等待服务启动
    sleep 3

    if systemctl is-active --quiet $SERVICE_NAME; then
        echo -e "${GREEN}✅ 服务启动成功${NC}"
    else
        echo -e "${RED}❌ 服务启动失败${NC}"
        echo -e "${YELLOW}查看日志: sudo journalctl -u $SERVICE_NAME -n 50${NC}"
        exit 1
    fi
}

# 验证配置
verify_config() {
    echo -e "${BLUE}🔍 验证配置...${NC}"

    # 等待服务完全启动
    sleep 5

    # 检查健康状态
    health_response=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:3003/health)

    if [ "$health_response" == "200" ]; then
        echo -e "${GREEN}✅ 健康检查通过${NC}"
    else
        echo -e "${RED}❌ 健康检查失败 (HTTP: $health_response)${NC}"
        return 1
    fi

    echo -e "${GREEN}🎉 配置验证通过！${NC}"
    return 0
}

# 显示部署结果
show_results() {
    echo ""
    echo "=================================================="
    echo -e "${GREEN}🎉 部署完成！${NC}"
    echo "=================================================="
    echo -e "📊 服务状态: ${GREEN}$(systemctl is-active $SERVICE_NAME)${NC}"
    echo -e "🌐 访问地址: ${BLUE}http://your-server-ip:3003${NC}"
    echo -e "🔍 健康检查: ${BLUE}http://your-server-ip:3003/health${NC}"
    echo ""
    echo -e "${YELLOW}💡 配置管理:${NC}"
    echo "• 配置文件: $ENV_FILE"
    echo "• 修改配置后重启: sudo systemctl restart $SERVICE_NAME"
    echo "• 查看配置: cat $ENV_FILE"
    echo ""
    echo -e "${BLUE}📝 查看日志: sudo journalctl -u $SERVICE_NAME -f${NC}"
}

# 主函数
main() {
    echo -e "${BLUE}ERP Mock Server 配置部署工具${NC}"
    echo -e "${BLUE}支持通过环境变量配置AppKey和AppSecret${NC}"
    echo ""

    check_root
    check_env_file
    show_config
    stop_service
    update_systemd_service
    start_service

    if verify_config; then
        show_results
    else
        echo -e "${RED}❌ 配置验证失败${NC}"
        exit 1
    fi
}

# 运行主函数
main "$@"
